/* eslint-disable react-native/no-inline-styles */
import React, { Component } from 'react';
import {
  View,
  StyleSheet,
  Text,
  Image,
  ScrollView,
  TouchableOpacity,
  Modal,
  Button,
  Platform,
  PermissionsAndroid
} from 'react-native';
import styled from 'styled-components';
import LinearGradient from 'react-native-linear-gradient';
// import { getToken } from '../../utils/auth';
// import ScanQRCode from './components/RNCamera';
import { Actions } from 'react-native-router-flux';
import Sound from 'react-native-sound'; // 播放声音组件
import { AudioRecorder, AudioUtils } from 'react-native-audio';
import { getUserInfo, getToken } from '../../../utils/auth';
import { appluEduTalkTypes } from '../../../api/index';
import Toast from 'antd-mobile-rn/lib/toast';

export default class talkDetails extends Component {
  constructor(props) {
    super(props);
    this.state = {
      title: '谈话详情',
      imgUrl: require('../../../assets/work/sportsRankings/backtrack.png'),
      language: '',
      isRecording: false, //是否正在录音
      isFinished: false, // 是否完成录音
      stoppedRecording: false, //是否停止了录音
      audioPath: AudioUtils.DocumentDirectoryPath + '/jwt_' + '.aac', //路径下的文件名
      filePath: '',
      hasPermission: undefined, //是否获取权限
      second: 0, // 录音时长
      timerStr: '00:00:00', //录音时长字符串
      policeInfo: {}, // 警员信息
      isShowTalkStatus: false, // 是否选择谈话情况选择框
      isShowTalkTypes: false, // 是否显示谈话类型选择框
      talkTypesList: [],
      talkStatusList: [],
      talkTypesLabel: '',
      talkStatusLabel: '',
      curStatusIndex: '', //选中的谈话情况
      curTypesIndex: '', // 选中的说话类型
      token: ''
    };
    this.prepareRecordingPath = this.prepareRecordingPath.bind(this); //执行录音的方法
    this.checkPermission = this.checkPermission.bind(this); //检测是否授权
    this._startTimer = this._startTimer.bind(this); //录音
    this._stopTimer = this._stopTimer.bind(this); //停止
    this.play = this.play.bind(this); //播放
    this.pause = this.pause.bind(this); //暂停
    this.finishRecording = this.finishRecording.bind(this);
  }
  prepareRecordingPath(audioPath) {
    AudioRecorder.prepareRecordingAtPath(audioPath, {
      SampleRate: 22050,
      Channels: 1,
      AudioQuality: 'Low', //录音质量
      AudioEncoding: 'aac', //录音格式
      AudioEncodingBitRate: 32000 //比特率
    });
  }

  checkPermission() {
    if (Platform.OS !== 'android') {
      return Promise.resolve(true);
    }

    const rationale = {
      title: '获取录音权限',
      message: 'XXX正请求获取麦克风权限用于录音,是否准许'
    };

    return PermissionsAndroid.request(
      PermissionsAndroid.PERMISSIONS.RECORD_AUDIO,
      rationale
    ).then(result => {
      return result === true || PermissionsAndroid.RESULTS.GRANTED;
    });
  }

  async _startTimer() {
    // this.setState({
    //   audioPath:
    //     AudioUtils.DocumentDirectoryPath +
    //     '/jwt_' +
    //     new Date().getTime() +
    //     '.aac'
    // });
    // 如果正在录音
    if (this.state.isRecording) {
      Toast.loading('正在录音中...', 1, () => {
        console.log('Load complete !!!');
      });
      return;
    }
    console.log(this.state.hasPermission, 82);
    //如果没有获取权限
    if (!this.state.hasPermission) {
      Toast.fail('没有获取录音权限', 1);
      return;
    }

    //如果暂停获取停止了录音
    if (this.state.stoppedRecording) {
      this.prepareRecordingPath(this.state.audioPath);
    }

    this.setState({ isRecording: true });

    try {
      const filePath = await AudioRecorder.startRecording();
    } catch (error) {
      console.error(error);
    }
  }

  async _stopTimer() {
    // 如果没有在录音
    if (!this.state.isRecording) {
      Toast.fail('没有录音, 无需停止!', 1);
      return;
    }

    this.setState({ stoppedRecording: true, isRecording: false });

    try {
      const filePath = await AudioRecorder.stopRecording();
      const _date = new Date().getTime();
      await this.setState({
        audioPath: AudioUtils.DocumentDirectoryPath + '/jwt_' + _date + '.aac'
      });
      if (Platform.OS === 'android') {
        this.finishRecording(true, filePath);
      }
      return filePath;
    } catch (error) {
      console.error(error);
    }
  }

  async play() {
    // 如果在录音 , 执行停止按钮
    if (this.state.isRecording) {
      await this.stop();
    }

    // 使用 setTimeout 是因为, 为避免发生一些问题 react-native-sound中
    setTimeout(() => {
      var sound = new Sound(this.state.audioPath, '', error => {
        if (error) {
          console.log('failed to load the sound', error);
        }
      });

      setTimeout(() => {
        sound.play(success => {
          if (success) {
            console.log('successfully finished playing');
          } else {
            console.log('playback failed due to audio decoding errors');
          }
        });
      }, 100);
    }, 100);
  }

  async pause() {
    if (!this.state.isRecording) {
      Toast.fail('没有录音, 无需停止!', 1);
      return;
    }
    this.setState({ stoppedRecording: true, isRecording: false });

    try {
      const filePath = await AudioRecorder.pauseRecording();

      // 在安卓中, 暂停就等于停止
      if (Platform.OS === 'android') {
        this.finishRecording(true, filePath);
      }
    } catch (error) {
      console.error(error);
    }
  }

  finishRecording(didSucceed, filePath) {
    this.setState({ isFinished: didSucceed, filePath });
    console.log(
      `Finished recording of duration ${
        this.state.second
      } seconds at path: ${filePath},---------------------${
        this.state.audioPath
      }`
    );
  }
  _matchTimer() {
    const h =
      Math.floor(this.state.second / 3600) < 10
        ? '0' + Math.floor(this.state.second / 3600)
        : Math.floor(this.state.second / 3600);
    const m =
      Math.floor(this.state.second / 60) < 10
        ? '0' + Math.floor(this.state.second / 60)
        : Math.floor(this.state.second / 60);
    const s =
      Math.floor(this.state.second % 60) < 10
        ? '0' + Math.floor(this.state.second % 60)
        : Math.floor(this.state.second % 60);
    this.setState({
      timerStr: h + ':' + m + ':' + s
    });
  }
  componentWillMount() {
    getToken().then(token => {
      this.setState({ token });
      appluEduTalkTypes(
        token,
        'educational_talk',
        this.state.curTypesIndex
      ).then(res => {
        if (res.code === '0') {
          this.setState({ talkTypesList: res.data });
        }
      });
    });
    getUserInfo().then(res => {
      console.log(JSON.stringify(res, null, 4), 222);
      this.setState({
        policeInfo: res.policeBaseInfoVo || null
      });
    });
  }

  componentDidMount() {
    // 页面加载完成后获取权限
    this.checkPermission().then(hasPermission => {
      this.setState({ hasPermission });
      //如果未授权, 则执行下面的代码
      if (!hasPermission) {
        return;
      }
      this.prepareRecordingPath(this.state.audioPath);
      AudioRecorder.onProgress = data => {
        this.setState({ second: Math.floor(data.currentTime) });
        this._matchTimer();
      };
      AudioRecorder.onFinished = data => {
        if (Platform.OS === 'ios') {
          this.finishRecording(data.status === 'OK', data.audioFileURL);
        }
      };
    });
  }
  render() {
    return (
      <ScrollView
        style={{
          flex: 1
        }}>
        <View style={styles.header}>
          <TouchableOpacity onPress={() => Actions.pop()}>
            <View>
              <Image
                source={this.state.imgUrl}
                style={{ width: 25.67, height: 22.33, marginBottom: 5 }}
              />
            </View>
          </TouchableOpacity>
          <Text
            style={{
              fontSize: 30,
              fontWeight: 'bold',
              borderBottomColor: '#EDEDED',
              borderBottomWidth: 1,
              borderBottomStyle: 'dashed'
            }}>
            {this.state.title}
          </Text>
        </View>
        <View style={{ padding: 20 }}>
          <LabelView
            style={{
              width: '100%',
              height: 126.67,
              backgroundColor: '#fff',
              padding: 20
            }}>
            <Text style={{ color: '#666666', fontSize: 16, marginBottom: 20 }}>
              {this.state.policeInfo.postName || '警务长'}
            </Text>
            <Text style={{ color: '#666666', fontSize: 12, marginBottom: 5 }}>
              警号：{this.state.policeInfo.policeCode || 'BBYKYHC'}
            </Text>
            <View
              style={{
                flexDirection: 'row',
                justifyContent: 'space-between',
                marginBottom: 5
              }}>
              <Text style={{ color: '#666666', fontSize: 12 }}>
                {this.state.policeInfo.cusName || '湖南省雨花区第二女子监狱'}
              </Text>
              <Text style={{ color: '#000000', fontSize: 18, lineHeight: 18 }}>
                {this.state.policeInfo.policeName || '张三峰'}
              </Text>
            </View>
            {this.state.policeInfo.photoUrl ? (
              <Image
                source={{ uri: this.state.policeInfo.photoUrl }}
                style={{
                  width: 41.33,
                  height: 41.33,
                  position: 'absolute',
                  top: 20.33,
                  right: 20.33
                }}
              />
            ) : (
              <Image
                source={require('../../../assets/work/eduTalk/avd.png')}
                style={{
                  width: 41.33,
                  height: 41.33,
                  position: 'absolute',
                  top: 20.33,
                  right: 20.33
                }}
              />
            )}
          </LabelView>
          <LabelView style={{ paddingLeft: 16, paddingRight: 16 }}>
            <BotLineView>
              <View>
                <LabelTitle>罪犯姓名</LabelTitle>
              </View>
              <View>
                <TouchableOpacity
                  onPress={() => {
                    console.log('点击扫码');
                    Actions.ScanQRCode();
                  }}>
                  <LabelTitle>点击扫码</LabelTitle>
                </TouchableOpacity>
              </View>
              {/* <LabelTitle style={{ color: '#666' }} /> */}
            </BotLineView>
            <BotLineView>
              <LabelTitle>罪犯扫码</LabelTitle>
              <LabelTitle style={{ color: '#666' }}>2150127</LabelTitle>
            </BotLineView>
            <BotLineView>
              <LabelTitle>罪犯部门</LabelTitle>
              <LabelTitle style={{ color: '#666' }}>缓刑部</LabelTitle>
            </BotLineView>
          </LabelView>
          <LabelView style={{ paddingLeft: 16, paddingRight: 16 }}>
            <BotLineView>
              <LabelTitle style={{ height: 48.33, lineHeight: 48.33 }}>
                谈话类型
              </LabelTitle>
            </BotLineView>
            <BotLineView>
              <View
                style={{
                  width: '45%',
                  height: 22,
                  backgroundColor: '#D6D6D9',
                  borderRadius: 11
                }}>
                <TouchableOpacity
                  style={{
                    width: '100%',
                    flexDirection: 'row',
                    justifyContent: 'space-around',
                    alignItems: 'center'
                  }}
                  onPress={() => {
                    console.log('请选择说话类型');
                    this.setState({ isShowTalkTypes: true });
                  }}>
                  <Text
                    style={{
                      color: '#fff',
                      fontSize: 10.67,
                      textAlign: 'center',
                      lineHeight: 22
                    }}>
                    {this.state.talkTypesLabel
                      ? this.state.talkTypesLabel
                      : '请选择说话类型'}
                  </Text>
                  <Image
                    source={require('../../../assets/work/eduDetails/select.png')}
                    style={{
                      width: 9.33,
                      height: 5.67
                    }}
                  />
                </TouchableOpacity>
              </View>
              <Modal
                animationType="fade" // 指定了 modal 的动画类型。类型：slide 从底部滑入滑出|fade 淡入淡出|none 没有动画
                transparent={true} // 背景是否透明，默认为白色，当为true时表示背景为透明。
                visible={this.state.isShowTalkTypes} // 是否显示 modal 窗口
                onRequestClose={() => {
                  // this._closeModalWin();
                  console.log('close Callback');
                }} // 回调会在用户按下 Android 设备上的后退按键或是 Apple TV 上的菜单键时触发。请务必注意本属性在 Android 平台上为必填，且会在 modal 处于开启状态时阻止BackHandler事件
                onShow={() => {
                  console.log('modal窗口显示了');
                  this.setState({ curTypesIndex: '' });
                }} // 回调函数会在 modal 显示时调用
              >
                <View style={styles.modalLayer}>
                  <View style={styles.modalContainer}>
                    <ScrollView>
                      {this.state.talkTypesList.map((e, idx) => (
                        <ScrollText
                          key={idx}
                          style={{
                            backgroundColor:
                              e.pdCode === this.state.curTypesIndex
                                ? '#ccc'
                                : '#fff',
                            color:
                              e.pdCode === this.state.curTypesIndex
                                ? '#fff'
                                : '#000'
                          }}
                          onPress={() => {
                            this.setState({
                              curTypesIndex: e.pdCode,
                              talkTypesLabel: e.pdName
                            });
                          }}>
                          {e.pdName}
                        </ScrollText>
                      ))}
                    </ScrollView>
                    <View style={styles.modalButtonStyle}>
                      <Button
                        title="确定"
                        color="#A4A4A4"
                        onPress={() => {
                          if (!this.state.curTypesIndex) {
                            Toast.info('请选择说话类型', 1, undefined, false);
                          } else {
                            if (this.state.curTypesIndex) {
                              appluEduTalkTypes(
                                this.state.token,
                                'educational_talk',
                                this.state.curTypesIndex
                              ).then(res => {
                                if (res.code === '0') {
                                  this.setState({ talkStatusList: res.data });
                                }
                              });
                            }
                            this.setState({ isShowTalkTypes: false });
                          }
                        }}
                      />
                    </View>
                  </View>
                </View>
              </Modal>
              <View
                style={{
                  width: '45%',
                  height: 22,
                  backgroundColor: '#D6D6D9',
                  color: '#fff',
                  borderRadius: 11
                }}>
                <TouchableOpacity
                  style={{
                    width: '100%',
                    flexDirection: 'row',
                    justifyContent: 'space-around',
                    alignItems: 'center'
                  }}
                  onPress={() => {
                    if (!this.state.curTypesIndex) {
                      Toast.info('请选择说话类型', 1, undefined, false);
                    } else {
                      this.setState({
                        isShowTalkStatus: true
                      });
                    }
                  }}>
                  <Text
                    style={{
                      color: '#fff',
                      lineHeight: 22,
                      fontSize: 10.67,
                      textAlign: 'center'
                    }}>
                    {this.state.talkStatusLabel
                      ? this.state.talkStatusLabel
                      : '请选择谈话情况'}
                  </Text>
                  <Image
                    source={require('../../../assets/work/eduDetails/select.png')}
                    style={{
                      width: 9.33,
                      height: 5.67
                    }}
                  />
                </TouchableOpacity>
              </View>
              <Modal
                animationType="fade" // 指定了 modal 的动画类型。类型：slide 从底部滑入滑出|fade 淡入淡出|none 没有动画
                transparent={true} // 背景是否透明，默认为白色，当为true时表示背景为透明。
                visible={this.state.isShowTalkStatus} // 是否显示 modal 窗口
                onRequestClose={() => {
                  // this._closeModalWin();
                  console.log('close Callback');
                }} // 回调会在用户按下 Android 设备上的后退按键或是 Apple TV 上的菜单键时触发。请务必注意本属性在 Android 平台上为必填，且会在 modal 处于开启状态时阻止BackHandler事件
                onShow={() => {
                  console.log('modal窗口显示了');
                  this.setState({ curStatusIndex: '' });
                }} // 回调函数会在 modal 显示时调用
              >
                <View style={styles.modalLayer}>
                  <View style={styles.modalContainer}>
                    <ScrollView>
                      {this.state.talkStatusList.length ? (
                        this.state.talkStatusList.map((e, idx) => (
                          <ScrollText
                            key={idx}
                            style={{
                              backgroundColor:
                                e.pdCode === this.state.curStatusIndex
                                  ? '#ccc'
                                  : '#fff',
                              color:
                                e.pdCode === this.state.curStatusIndex
                                  ? '#fff'
                                  : '#000'
                            }}
                            onPress={() => {
                              this.setState({
                                curStatusIndex: e.pdCode,
                                talkStatusLabel: e.pdName
                              });
                            }}>
                            {e.pdName}
                          </ScrollText>
                        ))
                      ) : (
                        <View
                          style={{
                            // flex: 1,
                            width: '100%',
                            height: '100%',
                            justifyContent: 'center',
                            textAlign: 'center',
                            alignItems: 'center'
                          }}>
                          <Text style={{ marginTop: 30 }}>暂无更多数据</Text>
                        </View>
                      )}
                    </ScrollView>
                    <View style={styles.modalButtonStyle}>
                      <Button
                        title="确定"
                        color="#A4A4A4"
                        onPress={() => {
                          // if (!this.state.curStatusIndex) {
                          //   alert('请选择谈话情况');
                          // } else {
                          this.setState({ isShowTalkStatus: false });
                          // }
                        }}
                      />
                    </View>
                  </View>
                </View>
              </Modal>
            </BotLineView>
          </LabelView>
          <LabelView style={{ paddingLeft: 16, paddingRight: 16 }}>
            <BotLineView>
              <LabelTitle>
                {this.state.isRecording
                  ? '正在录音：'
                  : this.state.isFinished
                  ? '录音结束：'
                  : '开始录音：'}
                {this.state.timerStr}
              </LabelTitle>
              <LabelTitle style={{ color: '#666', fontSize: 12 }}>
                <Image
                  source={require('../../../assets/work/eduDetails/tips.png')}
                  style={{ width: 12, height: 12 }}
                />
                &nbsp;根据谈话时长3分钟以上
              </LabelTitle>
            </BotLineView>
          </LabelView>
          <View
            style={{ flexDirection: 'row', justifyContent: 'space-between' }}>
            <CustomLinearGradient
              colors={['#51B6FC', '#7666FE']}
              start={{ x: 0, y: 0 }}
              end={{ x: 1, y: 1 }}>
              {this.state.isRecording ? (
                <OnTouchableOpacity
                  style={{
                    width: 140.33,
                    height: 29.33
                  }}
                  onPress={() => {
                    this._stopTimer();
                  }}>
                  <Text style={{ color: '#fff', fontSize: 12 }}>结束录音</Text>
                </OnTouchableOpacity>
              ) : (
                <OnTouchableOpacity
                  style={{
                    width: 140.33,
                    height: 29.33
                  }}
                  onPress={() => {
                    this._startTimer();
                  }}>
                  <Text style={{ color: '#fff', fontSize: 12 }}>开始录音</Text>
                </OnTouchableOpacity>
              )}
            </CustomLinearGradient>
            <CustomLinearGradient
              colors={['#51B6FC', '#7666FE']}
              start={{ x: 0, y: 0 }}
              end={{ x: 1, y: 1 }}>
              <OnTouchableOpacity
                style={{
                  width: 140.33,
                  height: 29.33
                }}
                onPress={() => {
                  if (!this.state.curTypesIndex) {
                    Toast.info('请选择谈话类型', 1, undefined, false);
                    return;
                  }
                  if (!this.state.curStatusIndex) {
                    Toast.info('请选择谈话情况', 1, undefined, false);
                    return;
                  }
                  if (this.state.second < 10) {
                    Toast.info(
                      '录音时长需大于三分钟，请重新录音',
                      1,
                      undefined,
                      false
                    );
                    return;
                  }
                  Actions.talkHandle({
                    info: {
                      pfiFileName: this.state.audioPath.split('/')[
                        this.state.audioPath.split('/').length - 1
                      ], // 文件名
                      pfiFilePath: this.state.audioPath, // 文件路径
                      pfiFileType: 1, // 文件类型
                      pfiFileRemark: '', // 描述
                      petPrisonerId: '', //罪犯信息编号
                      petTalkTime: this.state.timerStr,
                      petTalkTimeLong: this.state.second,
                      petTalkClassify: this.state.curTypesIndex,
                      petTalkType: this.state.curStatusIndex
                    }
                  });
                }}>
                <Text style={{ color: '#fff', fontSize: 12 }}>下一步</Text>
              </OnTouchableOpacity>
            </CustomLinearGradient>
          </View>
        </View>
      </ScrollView>
    );
  }
}

const styles = StyleSheet.create({
  header: {
    width: '100%',
    height: 98,
    backgroundColor: '#FFFFFF',
    padding: 19.33
  },
  container: {
    flex: 1
  },
  contentStyle: {
    padding: 30
  },
  contentTextStyle: {
    textAlign: 'center',
    fontSize: 26
  },
  modalLayer: {
    backgroundColor: 'rgba(0, 0, 0, 0.45)',
    flex: 1,
    justifyContent: 'center',
    padding: 32
  },
  modalContainer: {
    height: 300,
    backgroundColor: 'white'
    // justifyContent: 'center'
  },
  modalTitleStyle: {
    textAlign: 'center',
    fontSize: 26
  },
  modalButtonStyle: {
    paddingLeft: 30,
    paddingRight: 30,
    marginBottom: 10
  }
});
const OnTouchableOpacity = styled.TouchableOpacity`
  flex-direction: row;
  align-items: center;
  justify-content: center;
`;
const ScrollText = styled.Text`
  width: 100%;
  height: 60;
  text-align: center;
  line-height: 60;
  justify-content: center;
  border-bottom-width: 1;
  border-style: solid;
  border-color: #fafafa;
`;
const LabelView = styled.View`
  border-radius: 3.33;
  margin-bottom: 10.33;
  background: #fff;
`;
const BotLineView = styled.View`
  width: 100%;
  height: 48.33;
  flex-direction: row;
  justify-content: space-between;
  border-bottom-width: 1;
  border-style: solid;
  border-color: #fafafa;
`;
const LabelTitle = styled.Text`
  height: 48.33;
  line-height: 48.33;
`;
const CustomLinearGradient = styled(LinearGradient)`
  margin-left: 14;
  margin-top: 18.67;
  border-radius: 14.67;
`;
